package com.imu.purse.modules.bitcoin;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.googlecode.jsonrpc4j.JsonRpcHttpClient;
import com.imu.purse.bean.CoreMoneyAddr;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Map;

@Component
public class YtfcoinApi {
    private static Log log = LogFactory.get(BitcoinApi.class);
    /**
     * 初始化client
     */
    private JsonRpcHttpClient initClient(String moneyAddrStr){
        JsonRpcHttpClient client = null;
        try{
            Map<String,String> paramMap = Maps.newHashMap();
            //身份认证
            paramMap.put("Content-Type","application/json");
            CoreMoneyAddr moneyAddr = JSON.parseObject(moneyAddrStr,CoreMoneyAddr.class);
            client = new JsonRpcHttpClient(new URL(moneyAddr.getUrl() + ":" + moneyAddr.getPort()));
            client.setHeaders(paramMap);
        }catch (Exception e){
            log.error(e);
        }
        return client;
    }

    /**
     * 以太坊创建新用户
     * @param phone
     * @param moneyAddrStr
     * @return
     */
    public String createAccount(String phone,String moneyAddrStr){
        try{
            JsonRpcHttpClient client = initClient(moneyAddrStr);
            if(client != null){
                Object result = client.invoke("personal_newAccount", new Object[]{phone},Object.class);
                if(result != null){
                    return result.toString();
                }
            }
        }catch(Throwable e){
            log.error(e);
        }
        return null;
    }
}
